<template>
  <!-- 文章管理 详情 -->
  <div>
    <Breadcrumb></Breadcrumb>
    <div>
      <!-- 卡片栏 -->
      <el-card class="box-card">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <!-- <el-button type="primary" @click="handleFindUsers">查询</el-button> -->
            <el-button type="primary" @click="handleAddArticle"
              >发布文章</el-button
            >
            <!-- <el-button type="primary" @click="handleReset">重置</el-button> -->
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 文章信息 -->
    <div>
      <el-table :data="articleData" border style="width: 100%">
        <el-table-column fixed prop="date" label="文章标题" width="150">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.articleTitle }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="date" label="文章图片" width="150">
          <template slot-scope="scope">
            <div class="block">
              <el-image v-if="scope.row.articlePictureUrl === null"></el-image>
              <el-image
                v-else
                style="width: 100px; height: 100px"
                :src="imageUrl + '/' + scope.row.articlePictureUrl"
                :fit="fit"
              ></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="文章简介" width="120">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.articleIntro }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="作者" width="120">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="文章分类" width="120">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              scope.row.articleCategoryName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="province" label="评论数" width="120">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              scope.row.articleCommentCount
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="city" label="点赞数" width="120">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              scope.row.articleLikeCount
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="浏览记录" width="120">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              scope.row.articleViewCount
            }}</span>
          </template>
        </el-table-column>
        <!-- 操作按钮 -->
        <el-table-column fixed="right" label="操作" width="120px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleAddArticleImage(scope.$index, scope.row)"
              >修改文章封面</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 点击添加与编辑时显示的模态框 -->
    <el-dialog
      title="编辑文章"
      :visible.sync="dialogFormVisible"
      style="width: 100%"
      :fullscreen="true"
    >
      <el-form :model="formData">
        <el-form-item label="文 章 标 题：" :label-width="formLabelWidth">
          <el-input
            v-model="formData.articleTitle"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="文 章 简 介：" :label-width="formLabelWidth">
          <el-input
            v-model="formData.articleIntro"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="文 章 作 者：" :label-width="formLabelWidth">
          <el-input
            v-model="formData.articleAuthor"
            autocomplete="off"
            :disabled="isdisabled"
            style="width: 100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="文 章 类 型：" :label-width="formLabelWidth">
          <el-select
            v-model="value"
            clearable
            placeholder="请选择"
            @change="changeCategoryName"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.categoryName"
              :value="item.categoryName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item label="文 章 内 容：" label-width="100px">
          <div>
            <mavon-editor
              v-model="formData.articleContent"
              :ishljs="true"
              ref="md"
              @imgAdd="$imgAdd"
              @imgDel="$imgDel"
            />
          </div>
        </el-form-item>
      </el-form>
      <div></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addArticle">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改图片模态框 -->
    <el-dialog
      center
      title="修改文章封面"
      :visible.sync="dialogImageVisible"
      width="30%"
    >
      <!-- <span>这是一段信息</span> -->
      <el-upload
        class="imageDialog avatar-uploader"
        :limit="1"
        :action="uploadurl"
        list-type="picture-card"
        auto-upload
        :on-remove="handleRemove"
        :class="{ hide: hideUpload }"
        :on-change="imageChange"
        :before-upload="beforeAvatarUpload"
        :on-exceed="imageBeyond"
        :on-success="handleAvatarSuccess"
      >
        <img v-if="formData.avatarId" :src="dialogFormFullUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogImageVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleChangeArticleImage"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { quillEditor } from "vue-quill-editor";
import {
  getArticles,
  getArticleCategory,
  postArticle,
  putArticle,
  deleteArticle,
  InsterArticlePictureById,
  UploadImage,
} from "../api/article";
import marked from "marked";
import Breadcrumb from "./Breadcrumb";
import config from "../config/config";
export default {
  components: {
    Breadcrumb,
    // quillEditor,
  },
  // 初始化页面数据
  mounted() {
    //拉取文章详情
    getArticles().then(({ data }) => {
      console.log(data);
      for (let index = 0; index < data.data.length; index++) {
        // 获取内容
        var markdowncontent = data.data[index].articleContent;
        // md转html
        data.data[index].articleContent = marked(markdowncontent);
      }
      this.articleData = data.data;
    });
    // 拉取文章分类
    getArticleCategory().then(({ data }) => {
      this.options = data.data;
    });
  },
  data() {
    return {
      isdisabled: false,
      // 分类选项
      options: [],
      value: "",
      // 模态框宽度
      formLabelWidth: "120px",
      // 设置是否弹出Form模态框
      dialogFormVisible: false,
      // 设置是否弹出修改文章图片模糊框
      dialogImageVisible: false,
      // 设置
      disabled: false,
      // // 图片模态框 显示图片地址
      // dialogImageUrl: "",
      fit: "cover",
      // Form模态框数据
      formData: {
        articleId: 0,
        articleTitle: "",
        articleIntro: "",
        articleAuthor: "",
        articleContent: "",
        articleCategory: "",
      },
      title: "",
      // 表单的数据
      articleData: [],
      // // 图片绝对地址
      // pictureUrl: "",
      currentIndex: 0,
      hideUpload: false,
      // 用于添加文章图片
      imageData: {
        articleId: 0,
        articlePictureUrl: "",
      },
      dialogFormFullUrl: "",
    };
  },
  methods: {
    // 富文本编辑器图片上传
    $imgAdd(pos, $file) {
      console.log(pos);
      console.log($file);
      var formdata = new FormData();
      formdata.append("image", $file);
      UploadImage(formdata).then(({ data }) => {
        console.log(data);
        let imageUrl = config.baseURL + "/" + data.data.resultPath;
        this.$refs.md.$img2Url(pos, imageUrl);
      });
    },
    $imgDel(pos) {
      console.log(pos);
    },
    // 图片长传成功后动作
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.$message({
          type: "success",
          message: res.msg,
        });
      } else {
        let msg = "上传失败";
        this.$message.error(msg);
      }
      this.imageData.articlePictureUrl = res.data.resultPath;
    },
    // 图片超出提示
    imageBeyond() {
      this.$message.error("只能上传一张图片");
    },
    // 图片上传前校验
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount;
    },
    // 图片改变时出现的动作
    imageChange(file, fileList) {
      this.hideUpload = fileList.lenght >= this.limitCount;
    },
    // 添加文章封面按钮
    handleAddArticleImage(index, row) {
      console.log(row);
      this.currentIndex = index;
      this.imageData.articleId = row.articleId;
      // console.log(this.imageData);
      this.dialogImageVisible = true;
    },
    // 手动上传文章图片
    handleChangeArticleImage() {
      InsterArticlePictureById(this.imageData.articleId, this.imageData)
        .then(({ data }) => {
          if (data.code == 200) {
            this.articleData.splice(this.currentIndex, 1, data.data);
            // console.log(data);
            this.dialogImageVisible = false;
            this.$message({
              message: data.msg,
              type: "success",
            });
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 点击删除按钮
    handleDelete(index, row) {
      console.log(index);
      console.log(row);
      deleteArticle(row.articleId)
        .then(({ data }) => {
          if (data.code == 200) {
            this.$message({
              message: data.msg,
              type: "success",
            });
            this.articleData.splice(index, 1);
          }
        })
        .catch((err) => {
          this.$message(err);
        });
    },
    // 点击编辑按钮
    handleEdit(row, index) {
      console.log(row);
      this.formData.articleId = row.articleId;
      this.formData.articleTitle = row.articleTitle;
      this.formData.articleIntro = row.articleIntro;
      this.formData.articleContent = row.articleContent;
      this.formData.articleAuthor = row.userName;
      this.formData.articleCategory = row.articleCategoryName;
      this.value = row.articleCategoryName;
      this.dialogFormVisible = true;
      this.currentIndex = index;
      console.log(this.formData);
    },
    // 点击添加按钮
    handleAddArticle() {
      this.isdisabled = true;
      this.dialogFormVisible = !this.dialogFormVisible;
      this.formData.articleCategory = "";
      this.formData.articlePictureUrl = "";
      this.formData.articleAuthor = localStorage.getItem("username");
      this.formData.articleIntro = "";
      this.formData.articleTitle = "";
      this.formData.articleContent = "";
      this.value = "";
      this.currentIndex = 0;
    },
    // 改变下拉框的值时
    changeCategoryName(CategoryName) {
      this.formData.articleCategory = CategoryName;
    },
    // 添加文章与编辑文章模态框保存按钮
    addArticle() {
      console.log(this.content);
      console.log(this.formData);
      if (this.formData.articleId == 0) {
        postArticle(this.formData)
          .then(({ data }) => {
            if (data.code === 200) {
              // console.log(data);
              this.articleData.push(data.data);
              this.dialogFormVisible = false;
              this.$message({
                message: data.msg,
                type: "success",
              });
            } else {
              this.$message.error(data.msg);
            }
          })
          .catch((err) => {
            this.$message.error(err);
          });
      } else {
        putArticle(this.formData.articleId, this.formData)
          .then(({ data }) => {
            if (data.code == 200) {
              this.articleData.splice(this.currentIndex, 1, data.data);
              this.$message({
                type:'success',
                message:data.msg
              });
              this.dialogFormVisible = false;
            } else {
              this.$message.error("修改失败");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  },
  computed: {
    // 上传图片的地址
    uploadurl() {
      let baseUrl = config.baseURL;
      let uploadurl = "/File/UploadImage";
      return baseUrl + uploadurl;
    },
    imageUrl() {
      let baseURL = config.baseURL;
      return baseURL;
    },

    // editor() {
    //   return this.$refs.myQuillEditor.quill;
    // },
  },
};
</script>

<style scoped>
/* 使表格文字居中 */
::v-deep .el-table th,
::v-deep .el-table td {
  text-align: center !important;
}
.hide .el-upload--picture-card {
  display: none;
}
.imageDialog {
  display: flex;
  justify-content: center;
}
</style>

